package mobi.weq.servlets.data;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mobi.weq.dao.PollutionData;
import mobi.weq.model.SensorObservation;
import mobi.weq.util.edinburgh.EdinburghMap;

import com.google.gson.Gson;

/**
 * Servlet implementation class
 */
@WebServlet("/data/historical-data-for-location")
public class GetLastNDaysDataForALocation extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// lat, long
		// grid id
		String days = request.getParameter("days");
		String latString = request.getParameter("latitude");
		String lngString = request.getParameter("longitude");
		if (latString == null || lngString == null) {
			latString = EdinburghMap.CENTER_LAT + "";
			lngString = EdinburghMap.CENTER_LNG + "";
		}

		int n = Integer.parseInt(days);

		Gson g = new Gson();
		try {
			List<SensorObservation> list = PollutionData.getCurrentDataForPositionLastNDays(n, Double.valueOf(latString), Double.valueOf(lngString));
			response.getWriter().print(g.toJson(list));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
